package com.csxy.qiu.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.csxy.qiu.service.OssService;
import com.csxy.qiu.util.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl  implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        //TODO:上传头像到阿里云
        //工具类获取值
        String endpoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        String url = null;  //全局变量

        //输入流
        InputStream inputStream = null;
        try {

            //创建ossClient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            //获取文件
            inputStream = file.getInputStream();

            //获取文件名称
            String fileName = file.getOriginalFilename();

            //在文件名称添加唯一的uuid值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + fileName;

            //把文件按时间分类
            String datePath = new DateTime().toString("yyyy/MM/dd");
            fileName = datePath + "/" + fileName;

            //上传文件
            ossClient.putObject(bucketName, fileName, inputStream);

            //关闭ossClient
            ossClient.shutdown();

            //上传之后文件路径
             url = "https://" + bucketName + "." + endpoint + "/" + fileName;

            //Ctrl+alt+f,快速全局变量
        } catch (Exception e) {
            e.printStackTrace();
        }

        return url;
    }
}
